package com.caipos.service;

import com.caipos.entity.DeviceData;
import com.caipos.repository.jpa.DeviceDataJpaRepository;
import com.caipos.repository.redis.DeviceDataRedisRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class DeviceDataService {

    private final DeviceDataJpaRepository deviceDataJpaRepository;
    private final DeviceDataRedisRepository deviceDataRedisRepository;

    /**
     * 保存设备数据
     */
    @Transactional
    public void saveDeviceData(DeviceData deviceData) {
        // 保存到数据库
        DeviceData savedData = deviceDataJpaRepository.save(deviceData);
        // 缓存最近的数据
        deviceDataRedisRepository.save(savedData);
//        return savedData;
    }

    /**
     * 获取设备的最新数据
     */
    public List<DeviceData> getLatestDeviceData(String deviceId, int limit) {
        List<DeviceData> dataList = deviceDataJpaRepository.findByDeviceIdOrderByTimestampDesc(deviceId);
        return dataList.size() > limit ? dataList.subList(0, limit) : dataList;
    }

    /**
     * 获取设备特定类型的最新数据
     */
    public List<DeviceData> getLatestDeviceDataByType(String deviceId, String dataType, int limit) {
        List<DeviceData> dataList = deviceDataJpaRepository.findByDeviceIdAndDataTypeOrderByTimestampDesc(deviceId, dataType);
        return dataList.size() > limit ? dataList.subList(0, limit) : dataList;
    }
}
    